<template>
  <div class="video-player" @mousemove="showControls" @mouseleave="hideControls">
    <!-- 黑屏模式 -->
    <div v-if="isBlackScreenMode" class="black-screen">
      <div class="black-screen-content">
        <div class="black-screen-icon">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path
              d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
          </svg>
        </div>
        <div class="black-screen-text">等待中...</div>
        <div class="black-screen-time">{{ Math.ceil(blackScreenRemaining) }}秒</div>
      </div>
    </div>

    <!-- 正常视频模式 -->
    <video v-else ref="videoElement" class="video-element" :controls="false" @timeupdate="updateProgress"
      @loadedmetadata="onVideoLoaded" @ended="onVideoEnded" @click.stop.prevent="togglePlay" @play="onVideoPlay"
      @pause="onVideoPause">
      <source :src="src" :type="type">
      你的浏览器不支持视频播放
    </video>

    <!-- 视频控制层 -->
    <div class="video-overlay" :class="{ 'show-controls': showControlsFlag || isBlackScreenMode }">
      <!-- 中央播放按钮 -->
      <div class="play-button" @click="togglePlay" v-if="!isPlaying">
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M8 5v14l11-7z" />
        </svg>
      </div>

      <!-- 简化的底部控制栏 -->
      <div class="controls-bar">
        <!-- 移除音量按钮的黑屏限制 -->
        <button class="control-btn" @click="toggleMute">
          <svg v-if="!isMuted && volume > 0" viewBox="0 0 24 24" fill="currentColor">
            <path
              d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" />
          </svg>
          <svg v-else viewBox="0 0 24 24" fill="currentColor">
            <path
              d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z" />
          </svg>
        </button>

        <button class="control-btn" @click="toggleFullscreen">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
/* eslint-disable no-undef */
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'

// Props
const props = defineProps({
  src: {
    type: String,
    required: true
  },
  type: {
    type: String,
    default: 'video/mp4'
  },
  autoplay: {
    type: Boolean,
    default: false
  },
  externalCurrentTime: {
    type: Number,
    default: -1
  },
  shouldAutoPlay: {
    type: Boolean,
    default: false
  },
  blackScreenDuration: {
    type: Number,
    default: 0
  }
})

// Emits
const emit = defineEmits(['play-state-change', 'time-update', 'video-loaded', 'video-ended'])

// 响应式数据
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const volume = ref(1)
const isMuted = ref(false)
const showControlsFlag = ref(true)
const controlsTimer = ref(null)
const pendingPlay = ref(false)
const blackScreenTimer = ref(null)
const blackScreenStartTime = ref(0)
const blackScreenRemaining = ref(0)

// 模板引用
const videoElement = ref(null)

// 计算属性
const isBlackScreenMode = computed(() => {
  return props.blackScreenDuration > 0
})

// 方法
const clearBlackScreen = () => {
  if (blackScreenTimer.value) {
    clearInterval(blackScreenTimer.value)
    blackScreenTimer.value = null
  }
  blackScreenRemaining.value = 0
}

const startBlackScreen = (blackDuration) => {
  console.log(`🔵 开始黑屏模式，持续时间: ${blackDuration}秒`)
  console.log(`props.shouldAutoPlay: ${props.shouldAutoPlay}`)
  console.log(`pendingPlay: ${pendingPlay.value}`)
  console.log(`当前isPlaying: ${isPlaying.value}`)

  duration.value = blackDuration
  currentTime.value = 0
  blackScreenRemaining.value = blackDuration
  blackScreenStartTime.value = 0
  showControlsFlag.value = true

  emit('video-loaded', { duration: blackDuration })

  // 🔥 更强制的自动播放逻辑
  nextTick(() => {
    const shouldStart = props.shouldAutoPlay || pendingPlay.value
    console.log(`🚀 黑屏模式是否自动播放: ${shouldStart}`)

    if (shouldStart) {
      console.log('🚀 黑屏模式强制开始播放')
      isPlaying.value = true
      pendingPlay.value = false
      startBlackScreenTimer()
      emit('play-state-change', true)
    } else {
      console.log('⏸️ 黑屏模式不自动播放')
    }
  })
}

const startBlackScreenTimer = (fromTime = 0) => {
  clearBlackScreen()

  // 🔥 支持从指定时间开始计时
  const startOffset = fromTime * 1000  // 转换为毫秒
  blackScreenStartTime.value = Date.now() - startOffset
  console.log(`⏱️ 黑屏计时器开始: 从${fromTime}秒开始, 时间戳=${new Date(blackScreenStartTime.value).toLocaleTimeString()}`)

  blackScreenTimer.value = setInterval(() => {
    const elapsed = (Date.now() - blackScreenStartTime.value) / 1000
    currentTime.value = elapsed
    blackScreenRemaining.value = Math.max(0, duration.value - elapsed)

    emit('time-update', {
      currentTime: currentTime.value,
      duration: duration.value
    })

    if (elapsed >= duration.value) {
      onBlackScreenEnded()
    }
  }, 100)
}

const onBlackScreenEnded = () => {
  console.log('⏰ 黑屏时间结束，触发video-ended事件')
  console.log(`⏰ 黑屏持续时间: ${duration.value}秒`)
  console.log(`⏰ 实际经过时间: ${(Date.now() - blackScreenStartTime.value) / 1000}秒`)

  // 保存当前播放状态
  const wasPlayingBeforeEnd = isPlaying.value
  console.log(`⏰ 黑屏结束前是否在播放: ${wasPlayingBeforeEnd}`)

  clearBlackScreen()
  currentTime.value = duration.value
  emit('video-ended')

  // 延迟设置播放状态为false，给App.vue足够时间处理自动播放逻辑
  setTimeout(() => {
    isPlaying.value = false
    emit('play-state-change', false)
  }, 500)  // 增加延迟时间，确保App.vue能正确获取到播放状态
}

const tryPlay = () => {
  console.log(`tryPlay调用: pendingPlay=${pendingPlay.value}, isBlackScreenMode=${isBlackScreenMode.value}, duration=${duration.value}`)

  if (pendingPlay.value) {
    if (isBlackScreenMode.value) {
      console.log('📺 黑屏模式开始播放')
      play()
    } else if (videoElement.value && duration.value > 0) {
      console.log('🎬 视频模式开始播放')
      play()
    } else {
      console.log('⏳ 等待视频加载完成')
    }
  }
}

const play = () => {
  if (isBlackScreenMode.value) {
    isPlaying.value = true
    pendingPlay.value = false
    startBlackScreenTimer()
    emit('play-state-change', true)
  } else {
    if (!videoElement.value) return

    console.log('🎬 开始播放视频')
    videoElement.value.play().then(() => {
      console.log('🎬 视频播放成功')
      // onVideoPlay事件会处理状态更新
    }).catch(error => {
      console.warn('播放失败:', error)
      isPlaying.value = false
      pendingPlay.value = false
      emit('play-state-change', false)
    })
  }
}

const pause = () => {
  if (isBlackScreenMode.value) {
    isPlaying.value = false
    pendingPlay.value = false
    clearBlackScreen()
    emit('play-state-change', false)
  } else {
    if (!videoElement.value) return

    console.log('⏸️ 暂停视频')
    videoElement.value.pause()
    // onVideoPause事件会处理状态更新
  }
}

const updateProgress = () => {
  if (!videoElement.value || isBlackScreenMode.value) return

  currentTime.value = videoElement.value.currentTime

  // 🔥 关键修复：同步视频实际播放状态和UI状态
  const videoIsPlaying = !videoElement.value.paused && !videoElement.value.ended
  if (videoIsPlaying !== isPlaying.value) {
    console.log(`🔄 状态同步修复: 视频=${videoIsPlaying ? '播放中' : '已暂停'}, UI显示=${isPlaying.value ? '播放中' : '已暂停'}`)
    isPlaying.value = videoIsPlaying
    emit('play-state-change', videoIsPlaying)
  }

  emit('time-update', {
    currentTime: currentTime.value,
    duration: duration.value
  })
}

const onVideoLoaded = () => {
  if (!videoElement.value || isBlackScreenMode.value) return
  duration.value = videoElement.value.duration
  emit('video-loaded', {
    duration: duration.value
  })

  nextTick(() => {
    tryPlay()
  })
}

const onVideoEnded = () => {
  if (isBlackScreenMode.value) return

  isPlaying.value = false
  currentTime.value = 0

  emit('video-ended')
  emit('play-state-change', false)
}

const seekTo = (time) => {
  console.log(`🎯 seekTo被调用: time=${time}, 黑屏模式=${isBlackScreenMode.value}, 当前播放=${isPlaying.value}`)

  if (isBlackScreenMode.value) {
    // 🔥 在自动播放前提下，拖拽后始终保持播放状态
    if (!isPlaying.value) {
      console.log('🎯 拖拽后启动播放状态')
      isPlaying.value = true
      emit('play-state-change', true)
    }

    // 🔥 直接从指定时间开始黑屏计时器
    console.log('🎯 从指定时间重新启动黑屏计时器')
    startBlackScreenTimer(time)

    console.log(`🎯 黑屏跳转完成: time=${time}s, 剩余=${duration.value - time}s, 强制播放=true`)
  } else {
    if (!videoElement.value) return
    videoElement.value.currentTime = time
    currentTime.value = time
  }
}

const toggleMute = () => {
  if (isBlackScreenMode.value) {
    // 黑屏模式下只改变UI状态
    isMuted.value = !isMuted.value
    console.log(`🔇 黑屏模式切换静音状态: ${isMuted.value ? '静音' : '取消静音'}`)
  } else {
    // 正常视频模式
    if (!videoElement.value) return
    if (isMuted.value) {
      videoElement.value.volume = volume.value
      isMuted.value = false
    } else {
      volume.value = videoElement.value.volume
      videoElement.value.volume = 0
      isMuted.value = true
    }
  }
}

const toggleFullscreen = () => {
  const element = document.querySelector('.video-player')
  if (!document.fullscreenElement) {
    element.requestFullscreen().catch(error => {
      console.warn('全屏失败:', error)
    })
  } else {
    document.exitFullscreen().catch(error => {
      console.warn('退出全屏失败:', error)
    })
  }
}

const showControls = () => {
  showControlsFlag.value = true
  clearTimeout(controlsTimer.value)
  controlsTimer.value = setTimeout(() => {
    if (isPlaying.value) {
      showControlsFlag.value = false
    }
  }, 3000)
}

const hideControls = () => {
  if (isPlaying.value) {
    showControlsFlag.value = false
  }
}

// 暴露给父组件的方法
const externalPlay = () => {
  console.log(`🔥 externalPlay被调用: 黑屏模式=${isBlackScreenMode.value}, 当前播放=${isPlaying.value}`)

  if (isBlackScreenMode.value) {
    // 🔥 黑屏模式强制播放
    console.log('🔥 黑屏模式强制播放')
    isPlaying.value = true
    pendingPlay.value = false

    if (duration.value > 0) {
      startBlackScreenTimer()
    }

    emit('play-state-change', true)
  } else {
    // 正常视频播放
    play()
  }
}

const externalPause = () => {
  pause()
}

const externalSeek = (time) => {
  seekTo(time)
}

// 监听器
watch(() => props.src, (newSrc, oldSrc) => {
  if (newSrc !== oldSrc) {
    console.log(`VideoPlayer src changed: "${oldSrc}" -> "${newSrc}"`)
    currentTime.value = 0
    duration.value = 0

    if (!isBlackScreenMode.value) {
      clearBlackScreen()
    }

    if (isPlaying.value) {
      pendingPlay.value = true
    }

    nextTick(() => {
      if (videoElement.value && newSrc) {
        videoElement.value.load()
      }
    })
  }
})

watch(() => props.externalCurrentTime, (newTime) => {
  if (isBlackScreenMode.value) {
    if (newTime >= 0 && newTime <= duration.value) {
      console.log(`黑屏模式外部跳转到: ${newTime}秒`)

      // 使用 seekTo 方法来处理跳转，确保逻辑一致
      seekTo(newTime)
    }
  } else if (newTime >= 0 && videoElement.value && Math.abs(newTime - currentTime.value) > 1) {
    videoElement.value.currentTime = newTime
    currentTime.value = newTime
  }
})

watch(() => props.shouldAutoPlay, (shouldPlay) => {
  console.log(`shouldAutoPlay changed to: ${shouldPlay}`)
  console.log(`当前黑屏模式: ${isBlackScreenMode.value}`)
  console.log(`当前duration: ${duration.value}`)

  if (shouldPlay) {
    pendingPlay.value = true
    console.log('设置pendingPlay = true，准备tryPlay')
    nextTick(() => {
      tryPlay()
    })
  }
})

watch([() => props.src, () => props.blackScreenDuration], ([newSrc, newDuration], [oldSrc, oldDuration]) => {
  console.log(`VideoPlayer 组合状态变化: src="${oldSrc}" -> "${newSrc}", duration=${oldDuration} -> ${newDuration}`)
  console.log(`shouldAutoPlay: ${props.shouldAutoPlay}`)
  console.log(`当前播放状态: ${isPlaying.value}`)

  if (newDuration > 0) {
    console.log('🎯 检测到黑屏模式，开始初始化')
    clearBlackScreen()

    // 🔥 关键修复：如果之前在播放状态，强制设置自动播放
    const shouldAutoStart = props.shouldAutoPlay || isPlaying.value || pendingPlay.value
    console.log(`🔥 是否应该自动播放: ${shouldAutoStart} (shouldAutoPlay=${props.shouldAutoPlay}, isPlaying=${isPlaying.value}, pendingPlay=${pendingPlay.value})`)

    if (shouldAutoStart) {
      pendingPlay.value = true
    }

    nextTick(() => {
      startBlackScreen(newDuration)
    })
  } else if (oldDuration > 0 && newDuration === 0) {
    console.log('🎬 从黑屏模式切换到视频模式')
    clearBlackScreen()

    const shouldAutoStart = props.shouldAutoPlay || isPlaying.value || pendingPlay.value
    if (shouldAutoStart) {
      pendingPlay.value = true
    }
  }
}, { immediate: true })

// 暴露方法
defineExpose({
  externalPlay,
  externalPause,
  externalSeek
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    if (props.blackScreenDuration > 0) {
      startBlackScreen(props.blackScreenDuration)
    } else if (props.autoplay && videoElement.value) {
      play()
    }

    // 设置视频事件监听器
    if (videoElement.value) {
      setupVideoEventListeners()
    }
  })
})

onBeforeUnmount(() => {
  clearBlackScreen()
  if (controlsTimer.value) {
    clearTimeout(controlsTimer.value)
  }
  if (videoElement.value && !videoElement.value.paused) {
    videoElement.value.pause()
  }
})

// 修改togglePlay方法，移除防抖，直接处理
const togglePlay = () => {
  console.log(`🎮 togglePlay: UI状态=${isPlaying.value}, 黑屏=${isBlackScreenMode.value}`)

  if (isBlackScreenMode.value) {
    if (isPlaying.value) {
      pause()
    } else {
      play()
    }
  } else {
    if (!videoElement.value) return

    // 使用视频元素的实际状态，而不是UI状态
    const videoIsActuallyPlaying = !videoElement.value.paused && !videoElement.value.ended
    console.log(`🎮 视频实际状态: ${videoIsActuallyPlaying ? '播放中' : '已暂停'}`)

    if (videoIsActuallyPlaying) {
      pause()
    } else {
      play()
    }
  }
}

// 添加这些方法来处理视频原生事件
const onVideoPlay = () => {
  console.log('🎬 视频原生play事件触发')
  if (!isPlaying.value) {
    isPlaying.value = true
    emit('play-state-change', true)
  }
}

const onVideoPause = () => {
  console.log('⏸️ 视频原生pause事件触发')
  if (isPlaying.value) {
    isPlaying.value = false
    emit('play-state-change', false)
  }
}

// 添加这个方法
const setupVideoEventListeners = () => {
  if (!videoElement.value) return

  videoElement.value.addEventListener('play', () => {
    console.log('🎬 视频play事件 - 更新播放状态')
    if (!isPlaying.value) {
      isPlaying.value = true
      emit('play-state-change', true)
    }
  })

  videoElement.value.addEventListener('pause', () => {
    console.log('⏸️ 视频pause事件 - 更新暂停状态')
    if (isPlaying.value) {
      isPlaying.value = false
      emit('play-state-change', false)
    }
  })
}
</script>

<style scoped>
.video-player {
  position: relative;
  width: 100%;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.video-element {
  width: 100%;
  height: 100%;
  display: block;
  outline: none;
}

.video-element::-webkit-media-controls {
  display: none !important;
}

.video-element::-webkit-media-controls-panel {
  display: none !important;
}

.video-element::-webkit-media-controls-play-button {
  display: none !important;
}

.video-element::-webkit-media-controls-start-playback-button {
  display: none !important;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(transparent 60%, rgba(0, 0, 0, 0.7));
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  pointer-events: none;
}

.video-overlay.show-controls {
  opacity: 1;
  pointer-events: auto;
}

.play-button {
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.play-button:hover {
  background: rgba(255, 255, 255, 1);
  transform: scale(1.1);
}

.play-button svg {
  width: 36px;
  height: 36px;
  color: #333;
  margin-left: 4px;
}

.controls-bar {
  position: absolute;
  bottom: 0;
  right: 0;
  padding: 16px 20px 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  pointer-events: auto;
  justify-content: flex-end;
}

.control-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.control-btn svg {
  width: 24px;
  height: 24px;
}

.black-screen {
  width: 100%;
  height: 100%;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

.black-screen-content {
  text-align: center;
  color: white;
}

.black-screen-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  opacity: 0.6;
}

.black-screen-icon svg {
  width: 100%;
  height: 100%;
}

.black-screen-text {
  font-size: 18px;
  margin-bottom: 10px;
  opacity: 0.8;
}

.black-screen-time {
  font-size: 24px;
  font-weight: bold;
  color: #60a5fa;
}

/* 黑屏模式下的控制栏样式 */
.video-overlay.black-screen-mode .controls-bar {
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.video-overlay.black-screen-mode .control-btn {
  background: rgba(255, 255, 255, 0.1);
}

.video-overlay.black-screen-mode .control-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}
</style>